﻿using System;
//using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace Caculator {
	class Math {
		#region Fields
		public const double EPSILON	= 1.0E-15;
		public const double PI		= 3.141592653589793;
		public const double E		= 2.718281828459045;
		#endregion
		#region Methods
		public static double sin(double _x) {
			_x %= (2 * Math.PI);
			double rv = 0;
			double x = _x;
			int i = 0;
			do {
				rv += x; // cong so hang tiep theo cua tong vao gia tri cua sin
				x *= -(_x * _x) / (4 * ++i * i + 2 * i); // tinh so hang tiep theo cua tong
			} while (System.Math.Abs(x) > EPSILON);
			if (System.Math.Abs(rv) < EPSILON) rv = 0;
			return rv;
		}
		public static double cos(double _x) {
			_x %= (2 * Math.PI);
			double rv = 0;
			double x = 1.0;
			int i = 0;
			do {
				rv += x;
				x *= -(_x * _x) / (4 * ++i * i - 2 * i);
			} while (System.Math.Abs(x) > EPSILON);
			if (System.Math.Abs(rv) < EPSILON) rv = 0;
			return rv;
		}
		public static double tan(double _x) {
			_x %= (2 * Math.PI);
			double rv;
			try {
				rv = sin(_x) / cos(_x);
			}
			catch (DivideByZeroException) {
				rv = (_x > 0) ? Double.PositiveInfinity : Double.NegativeInfinity;
			};
			if (System.Math.Abs(rv) < EPSILON) rv = 0;
			return rv;
		}
		public static double cot(double _x) {
			_x %= (2 * Math.PI); 
			double rv = (_x > Math.PI / 2) ? Double.PositiveInfinity : Double.NegativeInfinity;
			try {
				rv = cos(_x) / sin(_x);
			}
			catch (DivideByZeroException) {
				rv = (_x > Math.PI / 2) ? Double.PositiveInfinity : Double.NegativeInfinity;
			}
			if (System.Math.Abs(rv) < EPSILON) rv = 0;
			return rv;
		}
		public static double sqrt(double _x) {
			//*
			double rv = _x;
			do {
				rv = 0.5 * rv + 0.5 *(_x / rv);
			} while (System.Math.Abs(0.5 * (_x / rv) - 0.5 * rv) > EPSILON);
			return rv;
			//*/
		}
		#endregion
	}
}
